// post-editor.js
const { categories } = require('../../utils/data');
const i18n = require('../../utils/i18n/index');

Page({
  data: {
    post: {
      title: '',
      content: '',
      category: '',
      tags: [],
      coverImage: '',
      excerpt: ''
    },
    categories: [],
    currentTag: '',
    formats: {},
    editorCtx: null,
    showCategoryPicker: false,
    isPreview: false,
    isSaving: false,
    isFullscreen: false,
    currentLanguage: 'en',
    t: {} // Translations
  },
  
  onLoad: function() {
    // Get app instance to access global language setting
    const app = getApp();
    const currentLanguage = app.globalData?.language || 'en';
    
    this.setData({
      categories: categories.map(cat => cat.name),
      currentLanguage
    });
    
    // Load translations
    this.loadLanguage(currentLanguage);
  },
  
  // Load translations based on selected language
  loadLanguage(lang) {
    const translations = i18n.getTranslations(lang);
    this.setData({
      t: translations,
      currentLanguage: lang
    });
  },
  
  // Handle language change from navigation bar
  onLanguageChange(e) {
    const lang = e.detail.language;
    this.loadLanguage(lang);
  },
  
  onReady: function() {
    // Create editor context after page is ready
    this.createEditorContext();
  },
  
  createEditorContext() {
    const selector = this.data.isFullscreen ? '#fullscreen-editor' : '#editor';
    this.createSelectorQuery().select(selector).context(res => {
      this.editorCtx = res.context;
      // Initialize editor with default formatting
      this.editorCtx.setContents({
        html: this.data.post.content || '<p>Start writing your post here...</p>',
        delta: {}
      });
    }).exec();
  },
  
  // Title input handler
  onTitleInput(e) {
    this.setData({
      'post.title': e.detail.value
    });
  },
  
  // Excerpt input handler
  onExcerptInput(e) {
    this.setData({
      'post.excerpt': e.detail.value
    });
  },
  
  // Category selection
  onCategoryTap() {
    this.setData({
      showCategoryPicker: true
    });
  },
  
  onCategoryPickerClose() {
    this.setData({
      showCategoryPicker: false
    });
  },
  
  onCategorySelect(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      'post.category': category,
      showCategoryPicker: false
    });
  },
  
  // Tag management
  onTagInput(e) {
    this.setData({
      currentTag: e.detail.value
    });
  },
  
  onAddTag() {
    const tag = this.data.currentTag.trim();
    if (tag && !this.data.post.tags.includes(tag)) {
      this.setData({
        'post.tags': [...this.data.post.tags, tag],
        currentTag: ''
      });
    }
  },
  
  onRemoveTag(e) {
    const tagIndex = e.currentTarget.dataset.index;
    const tags = [...this.data.post.tags];
    tags.splice(tagIndex, 1);
    this.setData({
      'post.tags': tags
    });
  },
  
  // Editor format handlers
  format(e) {
    const { name, value } = e.target.dataset;
    if (!name) return;
    
    this.editorCtx.format(name, value);
  },
  
  onStatusChange(e) {
    const formats = e.detail;
    this.setData({ formats });
  },
  
  insertImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.editorCtx.insertImage({
          src: tempFilePath,
          alt: 'image',
          width: '100%'
        });
      }
    });
  },
  
  // Cover image selection
  onChooseCoverImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          'post.coverImage': tempFilePath
        });
      }
    });
  },
  
  // Preview toggle
  togglePreview() {
    if (!this.data.isPreview) {
      // Get content from editor before preview
      this.editorCtx.getContents({
        success: res => {
          this.setData({
            'post.content': res.html,
            isPreview: !this.data.isPreview
          });
        }
      });
    } else {
      this.setData({
        isPreview: !this.data.isPreview
      });
    }
  },
  
  // Fullscreen toggle
  toggleFullscreen() {
    // Get current content before switching
    if (this.editorCtx) {
      this.editorCtx.getContents({
        success: res => {
          const currentContent = res.html;
          
          // Toggle fullscreen state
          const isFullscreen = !this.data.isFullscreen;
          this.setData({ isFullscreen });
          
          // Recreate editor context after state change
          setTimeout(() => {
            this.createEditorContext();
            
            // If entering fullscreen, focus the editor
            if (isFullscreen) {
              setTimeout(() => {
                if (this.editorCtx) {
                  this.editorCtx.focus();
                }
              }, 300);
            }
            
            // When exiting fullscreen, scroll back to the editor position
            if (!isFullscreen) {
              setTimeout(() => {
                wx.pageScrollTo({
                  selector: '#editor',
                  duration: 300
                });
              }, 100);
            }
          }, 100);
        }
      });
    } else {
      // If editor context is not available, just toggle the state
      this.setData({ isFullscreen: !this.data.isFullscreen });
      setTimeout(() => {
        this.createEditorContext();
      }, 100);
    }
  },
  
  // Save post
  savePost() {
    if (this.data.isSaving) return;
    
    // Validate required fields
    if (!this.data.post.title) {
      wx.showToast({
        title: 'Please enter a title',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ isSaving: true });
    
    // Get content from editor
    this.editorCtx.getContents({
      success: res => {
        const post = {
          ...this.data.post,
          content: res.html,
          date: new Date().toISOString().split('T')[0]
        };
        
        console.log('Saving post:', post);
        
        // In a real app, you would save to a database here
        // For now, just show success and go back
        wx.showToast({
          title: 'Post saved successfully!',
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      },
      fail: err => {
        console.error('Failed to get contents:', err);
        this.setData({ isSaving: false });
        wx.showToast({
          title: 'Failed to save post',
          icon: 'error'
        });
      }
    });
  },
  
  // Cancel editing
  cancelEditing() {
    wx.showModal({
      title: 'Discard changes?',
      content: 'All unsaved changes will be lost.',
      confirmText: 'Discard',
      confirmColor: '#ff4d4f',
      success: res => {
        if (res.confirm) {
          wx.navigateBack();
        }
      }
    });
  }
})